/**
 * 
 */
package mm.front.jsf.converters;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import mm.back.entity.Rubro;
import mm.back.service.RubroService;
import mm.exceptions.MMGenericException;

import org.springframework.web.jsf.FacesContextUtils;

/**
 * @author PUSDERKIS
 *
 */
public class RubroConverter implements Converter {

	private static RubroService rubroService;
	
	/**
	 * 
	 */
	public RubroConverter() {
		if (rubroService == null){
			rubroService = (RubroService)FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()).getBean("rubroService");
		}
		
	}


	/** 
	 * @see javax.faces.convert.Converter#getAsString(javax.faces.context.FacesContext, javax.faces.component.UIComponent, java.lang.Object)
	 */
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (!(value instanceof Rubro)){
			throw new MMGenericException("El objeto que se intenta convertir no es un Rubro.");
		}
		return ((Rubro)value).getId().toString();
	}


	/**
	 * @see javax.faces.convert.Converter#getAsObject(FacesContext, UIComponent, String)
	 */
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		try{
			Rubro r = rubroService.getRubro(Long.valueOf(value)); 
			return r;
		}catch (Exception e) {
			FacesMessage fm = new FacesMessage("No se puede recuperar el rubro seleccionado.","El id no existe en la base de datos.");
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ConverterException(fm);
		}
	}

}
